
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Time zones &#8212; Django 3.2.6.dev 文档</title>
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <script type="text/javascript" src="../../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../../genindex.html" />
    <link rel="search" title="搜索" href="../../search.html" />
    <link rel="next" title="Logging" href="../logging.html" />
    <link rel="prev" title="Format localization" href="formatting.html" />



 
<script src="../../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django 3.2.6.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="formatting.html" title="Format localization">previous</a>
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="../logging.html" title="Logging">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="topics-i18n-timezones">
            
  <div class="section" id="s-time-zones">
<span id="time-zones"></span><h1>Time zones<a class="headerlink" href="#time-zones" title="永久链接至标题">¶</a></h1>
<div class="section" id="s-overview">
<span id="s-time-zones-overview"></span><span id="overview"></span><span id="time-zones-overview"></span><h2>Overview<a class="headerlink" href="#overview" title="永久链接至标题">¶</a></h2>
<p>When support for time zones is enabled, Django stores datetime information in
UTC in the database, uses time-zone-aware datetime objects internally, and
translates them to the end user's time zone in templates and forms.</p>
<p>This is handy if your users live in more than one time zone and you want to
display datetime information according to each user's wall clock.</p>
<p>Even if your website is available in only one time zone, it's still good
practice to store data in UTC in your database. The main reason is Daylight
Saving Time (DST). Many countries have a system of DST, where clocks are moved
forward in spring and backward in autumn. If you're working in local time,
you're likely to encounter errors twice a year, when the transitions happen.
(The <a class="reference external" href="http://pytz.sourceforge.net/">pytz</a> documentation discusses <a class="reference external" href="http://pytz.sourceforge.net/#problems-with-localtime">these issues</a> in greater detail.) This
probably doesn't matter for your blog, but it's a problem if you over-bill or
under-bill your customers by one hour, twice a year, every year. The solution
to this problem is to use UTC in the code and use local time only when
interacting with end users.</p>
<p>Time zone support is disabled by default. To enable it, set <a class="reference internal" href="../../ref/settings.html#std:setting-USE_TZ"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_TZ</span> <span class="pre">=</span>
<span class="pre">True</span></code></a> in your settings file. By default, time zone support uses <a class="reference external" href="http://pytz.sourceforge.net/">pytz</a>,
which is installed when you install Django; Django also supports the use of
other time zone implementations like <a class="reference external" href="https://docs.python.org/3/library/zoneinfo.html#module-zoneinfo" title="(在 Python v3.9)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">zoneinfo</span></code></a> by passing
<a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.tzinfo" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> objects directly to functions in
<a class="reference internal" href="../../ref/utils.html#module-django.utils.timezone" title="django.utils.timezone: Timezone support."><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.utils.timezone</span></code></a>.</p>
<div class="versionchanged">
<span class="title">Changed in Django 3.2:</span> <p>Support for non-<code class="docutils literal notranslate"><span class="pre">pytz</span></code> timezone implementations was added.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">The default <code class="file docutils literal notranslate"><span class="pre">settings.py</span></code> file created by <a class="reference internal" href="../../ref/django-admin.html#django-admin-startproject"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">django-admin</span>
<span class="pre">startproject</span></code></a> includes <a class="reference internal" href="../../ref/settings.html#std:setting-USE_TZ"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_TZ</span> <span class="pre">=</span> <span class="pre">True</span></code></a>
for convenience.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">There is also an independent but related <a class="reference internal" href="../../ref/settings.html#std:setting-USE_L10N"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_L10N</span></code></a> setting that
controls whether Django should activate format localization. See
<a class="reference internal" href="formatting.html"><span class="doc">Format localization</span></a> for more details.</p>
</div>
<p>If you're wrestling with a particular problem, start with the <a class="reference internal" href="#time-zones-faq"><span class="std std-ref">time zone
FAQ</span></a>.</p>
</div>
<div class="section" id="s-concepts">
<span id="concepts"></span><h2>Concepts<a class="headerlink" href="#concepts" title="永久链接至标题">¶</a></h2>
<div class="section" id="s-naive-and-aware-datetime-objects">
<span id="s-naive-vs-aware-datetimes"></span><span id="naive-and-aware-datetime-objects"></span><span id="naive-vs-aware-datetimes"></span><h3>Naive and aware datetime objects<a class="headerlink" href="#naive-and-aware-datetime-objects" title="永久链接至标题">¶</a></h3>
<p>Python's <a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.datetime" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.datetime</span></code></a> objects have a <code class="docutils literal notranslate"><span class="pre">tzinfo</span></code> attribute that
can be used to store time zone information, represented as an instance of a
subclass of <a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.tzinfo" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.tzinfo</span></code></a>. When this attribute is set and describes
an offset, a datetime object is <strong>aware</strong>. Otherwise, it's <strong>naive</strong>.</p>
<p>You can use <a class="reference internal" href="../../ref/utils.html#django.utils.timezone.is_aware" title="django.utils.timezone.is_aware"><code class="xref py py-func docutils literal notranslate"><span class="pre">is_aware()</span></code></a> and
<a class="reference internal" href="../../ref/utils.html#django.utils.timezone.is_naive" title="django.utils.timezone.is_naive"><code class="xref py py-func docutils literal notranslate"><span class="pre">is_naive()</span></code></a> to determine whether datetimes are
aware or naive.</p>
<p>When time zone support is disabled, Django uses naive datetime objects in local
time. This is sufficient for many use cases. In this mode, to obtain the
current time, you would write:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">datetime</span>

<span class="n">now</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">()</span>
</pre></div>
</div>
<p>When time zone support is enabled (<a class="reference internal" href="../../ref/settings.html#std:setting-USE_TZ"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_TZ=True</span></code></a>), Django uses
time-zone-aware datetime objects. If your code creates datetime objects, they
should be aware too. In this mode, the example above becomes:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.utils</span> <span class="kn">import</span> <span class="n">timezone</span>

<span class="n">now</span> <span class="o">=</span> <span class="n">timezone</span><span class="o">.</span><span class="n">now</span><span class="p">()</span>
</pre></div>
</div>
<div class="admonition warning">
<p class="first admonition-title">警告</p>
<p class="last">Dealing with aware datetime objects isn't always intuitive. For instance,
the <code class="docutils literal notranslate"><span class="pre">tzinfo</span></code> argument of the standard datetime constructor doesn't work
reliably for time zones with DST. Using UTC is generally safe; if you're
using other time zones, you should review the <a class="reference external" href="http://pytz.sourceforge.net/">pytz</a> documentation
carefully.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p>Python's <a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.time" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.time</span></code></a> objects also feature a <code class="docutils literal notranslate"><span class="pre">tzinfo</span></code>
attribute, and PostgreSQL has a matching <code class="docutils literal notranslate"><span class="pre">time</span> <span class="pre">with</span> <span class="pre">time</span> <span class="pre">zone</span></code> type.
However, as PostgreSQL's docs put it, this type &quot;exhibits properties which
lead to questionable usefulness&quot;.</p>
<p class="last">Django only supports naive time objects and will raise an exception if you
attempt to save an aware time object, as a timezone for a time with no
associated date does not make sense.</p>
</div>
</div>
<div class="section" id="s-interpretation-of-naive-datetime-objects">
<span id="s-naive-datetime-objects"></span><span id="interpretation-of-naive-datetime-objects"></span><span id="naive-datetime-objects"></span><h3>Interpretation of naive datetime objects<a class="headerlink" href="#interpretation-of-naive-datetime-objects" title="永久链接至标题">¶</a></h3>
<p>When <a class="reference internal" href="../../ref/settings.html#std:setting-USE_TZ"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_TZ</span></code></a> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, Django still accepts naive datetime
objects, in order to preserve backwards-compatibility. When the database layer
receives one, it attempts to make it aware by interpreting it in the
<a class="reference internal" href="#default-current-time-zone"><span class="std std-ref">default time zone</span></a> and raises a warning.</p>
<p>Unfortunately, during DST transitions, some datetimes don't exist or are
ambiguous. In such situations, <a class="reference external" href="http://pytz.sourceforge.net/">pytz</a> raises an exception. That's why you should
always create aware datetime objects when time zone support is enabled.</p>
<p>In practice, this is rarely an issue. Django gives you aware datetime objects
in the models and forms, and most often, new datetime objects are created from
existing ones through <a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.timedelta" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a> arithmetic. The only
datetime that's often created in application code is the current time, and
<a class="reference internal" href="../../ref/utils.html#django.utils.timezone.now" title="django.utils.timezone.now"><code class="xref py py-func docutils literal notranslate"><span class="pre">timezone.now()</span></code></a> automatically does the
right thing.</p>
</div>
<div class="section" id="s-default-time-zone-and-current-time-zone">
<span id="s-default-current-time-zone"></span><span id="default-time-zone-and-current-time-zone"></span><span id="default-current-time-zone"></span><h3>Default time zone and current time zone<a class="headerlink" href="#default-time-zone-and-current-time-zone" title="永久链接至标题">¶</a></h3>
<p>The <strong>default time zone</strong> is the time zone defined by the <a class="reference internal" href="../../ref/settings.html#std:setting-TIME_ZONE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">TIME_ZONE</span></code></a>
setting.</p>
<p>The <strong>current time zone</strong> is the time zone that's used for rendering.</p>
<p>You should set the current time zone to the end user's actual time zone with
<a class="reference internal" href="../../ref/utils.html#django.utils.timezone.activate" title="django.utils.timezone.activate"><code class="xref py py-func docutils literal notranslate"><span class="pre">activate()</span></code></a>. Otherwise, the default time zone is
used.</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p>As explained in the documentation of <a class="reference internal" href="../../ref/settings.html#std:setting-TIME_ZONE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">TIME_ZONE</span></code></a>, Django sets
environment variables so that its process runs in the default time zone.
This happens regardless of the value of <a class="reference internal" href="../../ref/settings.html#std:setting-USE_TZ"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_TZ</span></code></a> and of the
current time zone.</p>
<p class="last">When <a class="reference internal" href="../../ref/settings.html#std:setting-USE_TZ"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_TZ</span></code></a> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, this is useful to preserve
backwards-compatibility with applications that still rely on local time.
However, <a class="reference internal" href="#naive-datetime-objects"><span class="std std-ref">as explained above</span></a>, this isn't
entirely reliable, and you should always work with aware datetimes in UTC
in your own code. For instance, use <a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.datetime.fromtimestamp" title="(在 Python v3.9)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fromtimestamp()</span></code></a>
and set the <code class="docutils literal notranslate"><span class="pre">tz</span></code> parameter to <a class="reference internal" href="../../ref/utils.html#django.utils.timezone.utc" title="django.utils.timezone.utc"><code class="xref py py-data docutils literal notranslate"><span class="pre">utc</span></code></a>.</p>
</div>
</div>
<div class="section" id="s-selecting-the-current-time-zone">
<span id="selecting-the-current-time-zone"></span><h3>Selecting the current time zone<a class="headerlink" href="#selecting-the-current-time-zone" title="永久链接至标题">¶</a></h3>
<p>The current time zone is the equivalent of the current <a class="reference internal" href="index.html#term-locale-name"><span class="xref std std-term">locale</span></a> for translations. However, there's no equivalent of the
<code class="docutils literal notranslate"><span class="pre">Accept-Language</span></code> HTTP header that Django could use to determine the user's
time zone automatically. Instead, Django provides <a class="reference internal" href="../../ref/utils.html#time-zone-selection-functions"><span class="std std-ref">time zone selection
functions</span></a>. Use them to build the time zone
selection logic that makes sense for you.</p>
<p>Most websites that care about time zones ask users in which time zone they live
and store this information in the user's profile. For anonymous users, they use
the time zone of their primary audience or UTC. <a class="reference external" href="http://pytz.sourceforge.net/">pytz</a> provides <a class="reference external" href="http://pytz.sourceforge.net/#helpers">helpers</a>, like a
list of time zones per country, that you can use to pre-select the most likely
choices.</p>
<p>Here's an example that stores the current timezone in the session. (It skips
error handling entirely for the sake of simplicity.)</p>
<p>Add the following middleware to <a class="reference internal" href="../../ref/settings.html#std:setting-MIDDLEWARE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MIDDLEWARE</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">pytz</span>

<span class="kn">from</span> <span class="nn">django.utils</span> <span class="kn">import</span> <span class="n">timezone</span>

<span class="k">class</span> <span class="nc">TimezoneMiddleware</span><span class="p">:</span>
    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">get_response</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">get_response</span> <span class="o">=</span> <span class="n">get_response</span>

    <span class="k">def</span> <span class="fm">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
        <span class="n">tzname</span> <span class="o">=</span> <span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;django_timezone&#39;</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">tzname</span><span class="p">:</span>
            <span class="n">timezone</span><span class="o">.</span><span class="n">activate</span><span class="p">(</span><span class="n">pytz</span><span class="o">.</span><span class="n">timezone</span><span class="p">(</span><span class="n">tzname</span><span class="p">))</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">timezone</span><span class="o">.</span><span class="n">deactivate</span><span class="p">()</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_response</span><span class="p">(</span><span class="n">request</span><span class="p">)</span>
</pre></div>
</div>
<p>Create a view that can set the current timezone:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="kn">import</span> <span class="n">redirect</span><span class="p">,</span> <span class="n">render</span>

<span class="k">def</span> <span class="nf">set_timezone</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">request</span><span class="o">.</span><span class="n">method</span> <span class="o">==</span> <span class="s1">&#39;POST&#39;</span><span class="p">:</span>
        <span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s1">&#39;django_timezone&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">request</span><span class="o">.</span><span class="n">POST</span><span class="p">[</span><span class="s1">&#39;timezone&#39;</span><span class="p">]</span>
        <span class="k">return</span> <span class="n">redirect</span><span class="p">(</span><span class="s1">&#39;/&#39;</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">render</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="s1">&#39;template.html&#39;</span><span class="p">,</span> <span class="p">{</span><span class="s1">&#39;timezones&#39;</span><span class="p">:</span> <span class="n">pytz</span><span class="o">.</span><span class="n">common_timezones</span><span class="p">})</span>
</pre></div>
</div>
<p>Include a form in <code class="docutils literal notranslate"><span class="pre">template.html</span></code> that will <code class="docutils literal notranslate"><span class="pre">POST</span></code> to this view:</p>
<div class="highlight-html+django notranslate"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">load</span> <span class="nv">tz</span> <span class="cp">%}</span>
<span class="cp">{%</span> <span class="k">get_current_timezone</span> <span class="k">as</span> <span class="nv">TIME_ZONE</span> <span class="cp">%}</span>
<span class="p">&lt;</span><span class="nt">form</span> <span class="na">action</span><span class="o">=</span><span class="s">&quot;</span><span class="cp">{%</span> <span class="k">url</span> <span class="s1">&#39;set_timezone&#39;</span> <span class="cp">%}</span><span class="s">&quot;</span> <span class="na">method</span><span class="o">=</span><span class="s">&quot;POST&quot;</span><span class="p">&gt;</span>
    <span class="cp">{%</span> <span class="k">csrf_token</span> <span class="cp">%}</span>
    <span class="p">&lt;</span><span class="nt">label</span> <span class="na">for</span><span class="o">=</span><span class="s">&quot;timezone&quot;</span><span class="p">&gt;</span>Time zone:<span class="p">&lt;/</span><span class="nt">label</span><span class="p">&gt;</span>
    <span class="p">&lt;</span><span class="nt">select</span> <span class="na">name</span><span class="o">=</span><span class="s">&quot;timezone&quot;</span><span class="p">&gt;</span>
        <span class="cp">{%</span> <span class="k">for</span> <span class="nv">tz</span> <span class="k">in</span> <span class="nv">timezones</span> <span class="cp">%}</span>
        <span class="p">&lt;</span><span class="nt">option</span> <span class="na">value</span><span class="o">=</span><span class="s">&quot;</span><span class="cp">{{</span> <span class="nv">tz</span> <span class="cp">}}</span><span class="s">&quot;</span><span class="cp">{%</span> <span class="k">if</span> <span class="nv">tz</span> <span class="o">==</span> <span class="nv">TIME_ZONE</span> <span class="cp">%}</span> <span class="na">selected</span><span class="cp">{%</span> <span class="k">endif</span> <span class="cp">%}</span><span class="p">&gt;</span><span class="cp">{{</span> <span class="nv">tz</span> <span class="cp">}}</span><span class="p">&lt;/</span><span class="nt">option</span><span class="p">&gt;</span>
        <span class="cp">{%</span> <span class="k">endfor</span> <span class="cp">%}</span>
    <span class="p">&lt;/</span><span class="nt">select</span><span class="p">&gt;</span>
    <span class="p">&lt;</span><span class="nt">input</span> <span class="na">type</span><span class="o">=</span><span class="s">&quot;submit&quot;</span> <span class="na">value</span><span class="o">=</span><span class="s">&quot;Set&quot;</span><span class="p">&gt;</span>
<span class="p">&lt;/</span><span class="nt">form</span><span class="p">&gt;</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="s-time-zone-aware-input-in-forms">
<span id="s-time-zones-in-forms"></span><span id="time-zone-aware-input-in-forms"></span><span id="time-zones-in-forms"></span><h2>Time zone aware input in forms<a class="headerlink" href="#time-zone-aware-input-in-forms" title="永久链接至标题">¶</a></h2>
<p>When you enable time zone support, Django interprets datetimes entered in
forms in the <a class="reference internal" href="#default-current-time-zone"><span class="std std-ref">current time zone</span></a> and returns
aware datetime objects in <code class="docutils literal notranslate"><span class="pre">cleaned_data</span></code>.</p>
<p>If the current time zone raises an exception for datetimes that don't exist or
are ambiguous because they fall in a DST transition (the timezones provided by
<a class="reference external" href="http://pytz.sourceforge.net/">pytz</a> do this), such datetimes will be reported as invalid values.</p>
</div>
<div class="section" id="s-time-zone-aware-output-in-templates">
<span id="s-time-zones-in-templates"></span><span id="time-zone-aware-output-in-templates"></span><span id="time-zones-in-templates"></span><h2>Time zone aware output in templates<a class="headerlink" href="#time-zone-aware-output-in-templates" title="永久链接至标题">¶</a></h2>
<p>When you enable time zone support, Django converts aware datetime objects to
the <a class="reference internal" href="#default-current-time-zone"><span class="std std-ref">current time zone</span></a> when they're rendered
in templates. This behaves very much like <a class="reference internal" href="formatting.html"><span class="doc">format localization</span></a>.</p>
<div class="admonition warning">
<p class="first admonition-title">警告</p>
<p class="last">Django doesn't convert naive datetime objects, because they could be
ambiguous, and because your code should never produce naive datetimes when
time zone support is enabled. However, you can force conversion with the
template filters described below.</p>
</div>
<p>Conversion to local time isn't always appropriate -- you may be generating
output for computers rather than for humans. The following filters and tags,
provided by the <code class="docutils literal notranslate"><span class="pre">tz</span></code> template tag library, allow you to control the time zone
conversions.</p>
<div class="section" id="s-template-tags">
<span id="template-tags"></span><h3>Template tags<a class="headerlink" href="#template-tags" title="永久链接至标题">¶</a></h3>
<div class="section" id="s-localtime">
<span id="s-std:templatetag-localtime"></span><span id="localtime"></span><span id="std:templatetag-localtime"></span><h4><code class="docutils literal notranslate"><span class="pre">localtime</span></code><a class="headerlink" href="#localtime" title="永久链接至标题">¶</a></h4>
<p>Enables or disables conversion of aware datetime objects to the current time
zone in the contained block.</p>
<p>This tag has exactly the same effects as the <a class="reference internal" href="../../ref/settings.html#std:setting-USE_TZ"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_TZ</span></code></a> setting as far
as the template engine is concerned. It allows a more fine grained control of
conversion.</p>
<p>To activate or deactivate conversion for a template block, use:</p>
<div class="highlight-html+django notranslate"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">load</span> <span class="nv">tz</span> <span class="cp">%}</span>

<span class="cp">{%</span> <span class="k">localtime</span> <span class="nv">on</span> <span class="cp">%}</span>
    <span class="cp">{{</span> <span class="nv">value</span> <span class="cp">}}</span>
<span class="cp">{%</span> <span class="k">endlocaltime</span> <span class="cp">%}</span>

<span class="cp">{%</span> <span class="k">localtime</span> <span class="nv">off</span> <span class="cp">%}</span>
    <span class="cp">{{</span> <span class="nv">value</span> <span class="cp">}}</span>
<span class="cp">{%</span> <span class="k">endlocaltime</span> <span class="cp">%}</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">The value of <a class="reference internal" href="../../ref/settings.html#std:setting-USE_TZ"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_TZ</span></code></a> isn't respected inside of a
<code class="docutils literal notranslate"><span class="pre">{%</span> <span class="pre">localtime</span> <span class="pre">%}</span></code> block.</p>
</div>
</div>
<div class="section" id="s-timezone">
<span id="s-std:templatetag-timezone"></span><span id="timezone"></span><span id="std:templatetag-timezone"></span><h4><code class="docutils literal notranslate"><span class="pre">timezone</span></code><a class="headerlink" href="#timezone" title="永久链接至标题">¶</a></h4>
<p>Sets or unsets the current time zone in the contained block. When the current
time zone is unset, the default time zone applies.</p>
<div class="highlight-html+django notranslate"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">load</span> <span class="nv">tz</span> <span class="cp">%}</span>

<span class="cp">{%</span> <span class="k">timezone</span> <span class="s2">&quot;Europe/Paris&quot;</span> <span class="cp">%}</span>
    Paris time: <span class="cp">{{</span> <span class="nv">value</span> <span class="cp">}}</span>
<span class="cp">{%</span> <span class="k">endtimezone</span> <span class="cp">%}</span>

<span class="cp">{%</span> <span class="k">timezone</span> <span class="kp">None</span> <span class="cp">%}</span>
    Server time: <span class="cp">{{</span> <span class="nv">value</span> <span class="cp">}}</span>
<span class="cp">{%</span> <span class="k">endtimezone</span> <span class="cp">%}</span>
</pre></div>
</div>
</div>
<div class="section" id="s-get-current-timezone">
<span id="s-std:templatetag-get_current_timezone"></span><span id="get-current-timezone"></span><span id="std:templatetag-get_current_timezone"></span><h4><code class="docutils literal notranslate"><span class="pre">get_current_timezone</span></code><a class="headerlink" href="#get-current-timezone" title="永久链接至标题">¶</a></h4>
<p>You can get the name of the current time zone using the
<code class="docutils literal notranslate"><span class="pre">get_current_timezone</span></code> tag:</p>
<div class="highlight-html+django notranslate"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">get_current_timezone</span> <span class="k">as</span> <span class="nv">TIME_ZONE</span> <span class="cp">%}</span>
</pre></div>
</div>
<p>Alternatively, you can activate the
<a class="reference internal" href="../../ref/templates/api.html#django.template.context_processors.tz" title="django.template.context_processors.tz"><code class="xref py py-func docutils literal notranslate"><span class="pre">tz()</span></code></a> context processor and
use the <code class="docutils literal notranslate"><span class="pre">TIME_ZONE</span></code> context variable.</p>
</div>
</div>
<div class="section" id="s-template-filters">
<span id="template-filters"></span><h3>Template filters<a class="headerlink" href="#template-filters" title="永久链接至标题">¶</a></h3>
<p>These filters accept both aware and naive datetimes. For conversion purposes,
they assume that naive datetimes are in the default time zone. They always
return aware datetimes.</p>
<div class="section" id="s-std:templatefilter-localtime">
<span id="s-id1"></span><span id="std:templatefilter-localtime"></span><span id="id1"></span><h4><code class="docutils literal notranslate"><span class="pre">localtime</span></code><a class="headerlink" href="#std:templatefilter-localtime" title="永久链接至标题">¶</a></h4>
<p>Forces conversion of a single value to the current time zone.</p>
<p>For example:</p>
<div class="highlight-html+django notranslate"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">load</span> <span class="nv">tz</span> <span class="cp">%}</span>

<span class="cp">{{</span> <span class="nv">value</span><span class="o">|</span><span class="nf">localtime</span> <span class="cp">}}</span>
</pre></div>
</div>
</div>
<div class="section" id="s-utc">
<span id="s-std:templatefilter-utc"></span><span id="utc"></span><span id="std:templatefilter-utc"></span><h4><code class="docutils literal notranslate"><span class="pre">utc</span></code><a class="headerlink" href="#utc" title="永久链接至标题">¶</a></h4>
<p>Forces conversion of a single value to UTC.</p>
<p>For example:</p>
<div class="highlight-html+django notranslate"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">load</span> <span class="nv">tz</span> <span class="cp">%}</span>

<span class="cp">{{</span> <span class="nv">value</span><span class="o">|</span><span class="nf">utc</span> <span class="cp">}}</span>
</pre></div>
</div>
</div>
<div class="section" id="s-std:templatefilter-timezone">
<span id="s-id2"></span><span id="std:templatefilter-timezone"></span><span id="id2"></span><h4><code class="docutils literal notranslate"><span class="pre">timezone</span></code><a class="headerlink" href="#std:templatefilter-timezone" title="永久链接至标题">¶</a></h4>
<p>Forces conversion of a single value to an arbitrary timezone.</p>
<p>The argument must be an instance of a <a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.tzinfo" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> subclass or a
time zone name.</p>
<p>For example:</p>
<div class="highlight-html+django notranslate"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">load</span> <span class="nv">tz</span> <span class="cp">%}</span>

<span class="cp">{{</span> <span class="nv">value</span><span class="o">|</span><span class="nf">timezone</span><span class="s2">:&quot;Europe/Paris&quot;</span> <span class="cp">}}</span>
</pre></div>
</div>
</div>
</div>
</div>
<div class="section" id="s-migration-guide">
<span id="s-time-zones-migration-guide"></span><span id="migration-guide"></span><span id="time-zones-migration-guide"></span><h2>Migration guide<a class="headerlink" href="#migration-guide" title="永久链接至标题">¶</a></h2>
<p>Here's how to migrate a project that was started before Django supported time
zones.</p>
<div class="section" id="s-database">
<span id="database"></span><h3>Database<a class="headerlink" href="#database" title="永久链接至标题">¶</a></h3>
<div class="section" id="s-postgresql">
<span id="postgresql"></span><h4>PostgreSQL<a class="headerlink" href="#postgresql" title="永久链接至标题">¶</a></h4>
<p>The PostgreSQL backend stores datetimes as <code class="docutils literal notranslate"><span class="pre">timestamp</span> <span class="pre">with</span> <span class="pre">time</span> <span class="pre">zone</span></code>. In
practice, this means it converts datetimes from the connection's time zone to
UTC on storage, and from UTC to the connection's time zone on retrieval.</p>
<p>As a consequence, if you're using PostgreSQL, you can switch between <code class="docutils literal notranslate"><span class="pre">USE_TZ</span>
<span class="pre">=</span> <span class="pre">False</span></code> and <code class="docutils literal notranslate"><span class="pre">USE_TZ</span> <span class="pre">=</span> <span class="pre">True</span></code> freely. The database connection's time zone
will be set to <a class="reference internal" href="../../ref/settings.html#std:setting-TIME_ZONE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">TIME_ZONE</span></code></a> or <code class="docutils literal notranslate"><span class="pre">UTC</span></code> respectively, so that Django
obtains correct datetimes in all cases. You don't need to perform any data
conversions.</p>
</div>
<div class="section" id="s-other-databases">
<span id="other-databases"></span><h4>Other databases<a class="headerlink" href="#other-databases" title="永久链接至标题">¶</a></h4>
<p>Other backends store datetimes without time zone information. If you switch
from <code class="docutils literal notranslate"><span class="pre">USE_TZ</span> <span class="pre">=</span> <span class="pre">False</span></code> to <code class="docutils literal notranslate"><span class="pre">USE_TZ</span> <span class="pre">=</span> <span class="pre">True</span></code>, you must convert your data from
local time to UTC -- which isn't deterministic if your local time has DST.</p>
</div>
</div>
<div class="section" id="s-code">
<span id="code"></span><h3>Code<a class="headerlink" href="#code" title="永久链接至标题">¶</a></h3>
<p>The first step is to add <a class="reference internal" href="../../ref/settings.html#std:setting-USE_TZ"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_TZ</span> <span class="pre">=</span> <span class="pre">True</span></code></a> to your settings
file. At this point, things should mostly work. If you create naive datetime
objects in your code, Django makes them aware when necessary.</p>
<p>However, these conversions may fail around DST transitions, which means you
aren't getting the full benefits of time zone support yet. Also, you're likely
to run into a few problems because it's impossible to compare a naive datetime
with an aware datetime. Since Django now gives you aware datetimes, you'll get
exceptions wherever you compare a datetime that comes from a model or a form
with a naive datetime that you've created in your code.</p>
<p>So the second step is to refactor your code wherever you instantiate datetime
objects to make them aware. This can be done incrementally.
<a class="reference internal" href="../../ref/utils.html#module-django.utils.timezone" title="django.utils.timezone: Timezone support."><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.utils.timezone</span></code></a> defines some handy helpers for compatibility
code: <a class="reference internal" href="../../ref/utils.html#django.utils.timezone.now" title="django.utils.timezone.now"><code class="xref py py-func docutils literal notranslate"><span class="pre">now()</span></code></a>,
<a class="reference internal" href="../../ref/utils.html#django.utils.timezone.is_aware" title="django.utils.timezone.is_aware"><code class="xref py py-func docutils literal notranslate"><span class="pre">is_aware()</span></code></a>,
<a class="reference internal" href="../../ref/utils.html#django.utils.timezone.is_naive" title="django.utils.timezone.is_naive"><code class="xref py py-func docutils literal notranslate"><span class="pre">is_naive()</span></code></a>,
<a class="reference internal" href="../../ref/utils.html#django.utils.timezone.make_aware" title="django.utils.timezone.make_aware"><code class="xref py py-func docutils literal notranslate"><span class="pre">make_aware()</span></code></a>, and
<a class="reference internal" href="../../ref/utils.html#django.utils.timezone.make_naive" title="django.utils.timezone.make_naive"><code class="xref py py-func docutils literal notranslate"><span class="pre">make_naive()</span></code></a>.</p>
<p>Finally, in order to help you locate code that needs upgrading, Django raises
a warning when you attempt to save a naive datetime to the database:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="ne">RuntimeWarning</span><span class="p">:</span> <span class="n">DateTimeField</span> <span class="n">ModelName</span><span class="o">.</span><span class="n">field_name</span> <span class="n">received</span> <span class="n">a</span> <span class="n">naive</span>
<span class="n">datetime</span> <span class="p">(</span><span class="mi">2012</span><span class="o">-</span><span class="mi">01</span><span class="o">-</span><span class="mi">01</span> <span class="mi">00</span><span class="p">:</span><span class="mi">00</span><span class="p">:</span><span class="mi">00</span><span class="p">)</span> <span class="k">while</span> <span class="n">time</span> <span class="n">zone</span> <span class="n">support</span> <span class="ow">is</span> <span class="n">active</span><span class="o">.</span>
</pre></div>
</div>
<p>During development, you can turn such warnings into exceptions and get a
traceback by adding the following to your settings file:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">warnings</span>
<span class="n">warnings</span><span class="o">.</span><span class="n">filterwarnings</span><span class="p">(</span>
    <span class="s1">&#39;error&#39;</span><span class="p">,</span> <span class="sa">r</span><span class="s2">&quot;DateTimeField .* received a naive datetime&quot;</span><span class="p">,</span>
    <span class="ne">RuntimeWarning</span><span class="p">,</span> <span class="sa">r</span><span class="s1">&#39;django\.db\.models\.fields&#39;</span><span class="p">,</span>
<span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="s-fixtures">
<span id="fixtures"></span><h3>Fixtures<a class="headerlink" href="#fixtures" title="永久链接至标题">¶</a></h3>
<p>When serializing an aware datetime, the UTC offset is included, like this:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="s2">&quot;2011-09-01T13:20:30+03:00&quot;</span>
</pre></div>
</div>
<p>While for a naive datetime, it isn't:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="s2">&quot;2011-09-01T13:20:30&quot;</span>
</pre></div>
</div>
<p>For models with <a class="reference internal" href="../../ref/models/fields.html#django.db.models.DateTimeField" title="django.db.models.DateTimeField"><code class="xref py py-class docutils literal notranslate"><span class="pre">DateTimeField</span></code></a>s, this difference
makes it impossible to write a fixture that works both with and without time
zone support.</p>
<p>Fixtures generated with <code class="docutils literal notranslate"><span class="pre">USE_TZ</span> <span class="pre">=</span> <span class="pre">False</span></code>, or before Django 1.4, use the
&quot;naive&quot; format. If your project contains such fixtures, after you enable time
zone support, you'll see <a class="reference external" href="https://docs.python.org/3/library/exceptions.html#RuntimeWarning" title="(在 Python v3.9)"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeWarning</span></code></a>s when you load them. To get
rid of the warnings, you must convert your fixtures to the &quot;aware&quot; format.</p>
<p>You can regenerate fixtures with <a class="reference internal" href="../../ref/django-admin.html#django-admin-loaddata"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">loaddata</span></code></a> then <a class="reference internal" href="../../ref/django-admin.html#django-admin-dumpdata"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">dumpdata</span></code></a>.
Or, if they're small enough, you can edit them to add the UTC offset that
matches your <a class="reference internal" href="../../ref/settings.html#std:setting-TIME_ZONE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">TIME_ZONE</span></code></a> to each serialized datetime.</p>
</div>
</div>
<div class="section" id="s-faq">
<span id="s-time-zones-faq"></span><span id="faq"></span><span id="time-zones-faq"></span><h2>FAQ<a class="headerlink" href="#faq" title="永久链接至标题">¶</a></h2>
<div class="section" id="s-setup">
<span id="setup"></span><h3>Setup<a class="headerlink" href="#setup" title="永久链接至标题">¶</a></h3>
<ol class="arabic">
<li><p class="first"><strong>I don't need multiple time zones. Should I enable time zone support?</strong></p>
<p>Yes. When time zone support is enabled, Django uses a more accurate model
of local time. This shields you from subtle and unreproducible bugs around
Daylight Saving Time (DST) transitions.</p>
<p>When you enable time zone support, you'll encounter some errors because
you're using naive datetimes where Django expects aware datetimes. Such
errors show up when running tests. You'll quickly learn how to avoid invalid
operations.</p>
<p>On the other hand, bugs caused by the lack of time zone support are much
harder to prevent, diagnose and fix. Anything that involves scheduled tasks
or datetime arithmetic is a candidate for subtle bugs that will bite you
only once or twice a year.</p>
<p>For these reasons, time zone support is enabled by default in new projects,
and you should keep it unless you have a very good reason not to.</p>
</li>
<li><p class="first"><strong>I've enabled time zone support. Am I safe?</strong></p>
<p>Maybe. You're better protected from DST-related bugs, but you can still
shoot yourself in the foot by carelessly turning naive datetimes into aware
datetimes, and vice-versa.</p>
<p>If your application connects to other systems -- for instance, if it queries
a Web service -- make sure datetimes are properly specified. To transmit
datetimes safely, their representation should include the UTC offset, or
their values should be in UTC (or both!).</p>
<p>Finally, our calendar system contains interesting edge cases. For example,
you can't always subtract one year directly from a given date:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">datetime</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">one_year_before</span><span class="p">(</span><span class="n">value</span><span class="p">):</span>  <span class="c1"># Wrong example.</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">value</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="n">year</span><span class="o">=</span><span class="n">value</span><span class="o">.</span><span class="n">year</span> <span class="o">-</span> <span class="mi">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">one_year_before</span><span class="p">(</span><span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="p">(</span><span class="mi">2012</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">0</span><span class="p">))</span>
<span class="go">datetime.datetime(2011, 3, 1, 10, 0)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">one_year_before</span><span class="p">(</span><span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="p">(</span><span class="mi">2012</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">29</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">0</span><span class="p">))</span>
<span class="gt">Traceback (most recent call last):</span>
<span class="c">...</span>
<span class="gr">ValueError</span>: <span class="n">day is out of range for month</span>
</pre></div>
</div>
<p>To implement such a function correctly, you must decide whether 2012-02-29
minus one year is 2011-02-28 or 2011-03-01, which depends on your business
requirements.</p>
</li>
<li><p class="first"><strong>How do I interact with a database that stores datetimes in local time?</strong></p>
<p>Set the <a class="reference internal" href="../../ref/settings.html#std:setting-DATABASE-TIME_ZONE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">TIME_ZONE</span></code></a> option to the appropriate
time zone for this database in the <a class="reference internal" href="../../ref/settings.html#std:setting-DATABASES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DATABASES</span></code></a> setting.</p>
<p>This is useful for connecting to a database that doesn't support time zones
and that isn't managed by Django when <a class="reference internal" href="../../ref/settings.html#std:setting-USE_TZ"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_TZ</span></code></a> is <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p>
</li>
</ol>
</div>
<div class="section" id="s-troubleshooting">
<span id="troubleshooting"></span><h3>Troubleshooting<a class="headerlink" href="#troubleshooting" title="永久链接至标题">¶</a></h3>
<ol class="arabic">
<li><p class="first"><strong>My application crashes with</strong> <code class="docutils literal notranslate"><span class="pre">TypeError:</span> <span class="pre">can't</span> <span class="pre">compare</span> <span class="pre">offset-naive</span></code>
<code class="docutils literal notranslate"><span class="pre">and</span> <span class="pre">offset-aware</span> <span class="pre">datetimes</span></code> <strong>-- what's wrong?</strong></p>
<p>Let's reproduce this error by comparing a naive and an aware datetime:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.utils</span> <span class="kn">import</span> <span class="n">timezone</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">aware</span> <span class="o">=</span> <span class="n">timezone</span><span class="o">.</span><span class="n">now</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">naive</span> <span class="o">=</span> <span class="n">timezone</span><span class="o">.</span><span class="n">make_naive</span><span class="p">(</span><span class="n">aware</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">naive</span> <span class="o">==</span> <span class="n">aware</span>
<span class="gt">Traceback (most recent call last):</span>
<span class="c">...</span>
<span class="gr">TypeError</span>: <span class="n">can&#39;t compare offset-naive and offset-aware datetimes</span>
</pre></div>
</div>
<p>If you encounter this error, most likely your code is comparing these two
things:</p>
<ul class="simple">
<li>a datetime provided by Django -- for instance, a value read from a form or
a model field. Since you enabled time zone support, it's aware.</li>
<li>a datetime generated by your code, which is naive (or you wouldn't be
reading this).</li>
</ul>
<p>Generally, the correct solution is to change your code to use an aware
datetime instead.</p>
<p>If you're writing a pluggable application that's expected to work
independently of the value of <a class="reference internal" href="../../ref/settings.html#std:setting-USE_TZ"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_TZ</span></code></a>, you may find
<a class="reference internal" href="../../ref/utils.html#django.utils.timezone.now" title="django.utils.timezone.now"><code class="xref py py-func docutils literal notranslate"><span class="pre">django.utils.timezone.now()</span></code></a> useful. This function returns the current
date and time as a naive datetime when <code class="docutils literal notranslate"><span class="pre">USE_TZ</span> <span class="pre">=</span> <span class="pre">False</span></code> and as an aware
datetime when <code class="docutils literal notranslate"><span class="pre">USE_TZ</span> <span class="pre">=</span> <span class="pre">True</span></code>. You can add or subtract
<a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.timedelta" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.timedelta</span></code></a> as needed.</p>
</li>
<li><p class="first"><strong>I see lots of</strong> <code class="docutils literal notranslate"><span class="pre">RuntimeWarning:</span> <span class="pre">DateTimeField</span> <span class="pre">received</span> <span class="pre">a</span> <span class="pre">naive</span>
<span class="pre">datetime</span></code> <code class="docutils literal notranslate"><span class="pre">(YYYY-MM-DD</span> <span class="pre">HH:MM:SS)</span></code> <code class="docutils literal notranslate"><span class="pre">while</span> <span class="pre">time</span> <span class="pre">zone</span> <span class="pre">support</span> <span class="pre">is</span> <span class="pre">active</span></code>
<strong>-- is that bad?</strong></p>
<p>When time zone support is enabled, the database layer expects to receive
only aware datetimes from your code. This warning occurs when it receives a
naive datetime. This indicates that you haven't finished porting your code
for time zone support. Please refer to the <a class="reference internal" href="#time-zones-migration-guide"><span class="std std-ref">migration guide</span></a> for tips on this process.</p>
<p>In the meantime, for backwards compatibility, the datetime is considered to
be in the default time zone, which is generally what you expect.</p>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">now.date()</span></code> <strong>is yesterday! (or tomorrow)</strong></p>
<p>If you've always used naive datetimes, you probably believe that you can
convert a datetime to a date by calling its <a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.datetime.date" title="(在 Python v3.9)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">date()</span></code></a>
method. You also consider that a <a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.date" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a> is a lot like a
<a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.datetime" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a>, except that it's less accurate.</p>
<p>None of this is true in a time zone aware environment:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">datetime</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">pytz</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">paris_tz</span> <span class="o">=</span> <span class="n">pytz</span><span class="o">.</span><span class="n">timezone</span><span class="p">(</span><span class="s2">&quot;Europe/Paris&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">new_york_tz</span> <span class="o">=</span> <span class="n">pytz</span><span class="o">.</span><span class="n">timezone</span><span class="p">(</span><span class="s2">&quot;America/New_York&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">paris</span> <span class="o">=</span> <span class="n">paris_tz</span><span class="o">.</span><span class="n">localize</span><span class="p">(</span><span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="p">(</span><span class="mi">2012</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">30</span><span class="p">))</span>
<span class="go"># This is the correct way to convert between time zones with pytz.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">new_york</span> <span class="o">=</span> <span class="n">new_york_tz</span><span class="o">.</span><span class="n">normalize</span><span class="p">(</span><span class="n">paris</span><span class="o">.</span><span class="n">astimezone</span><span class="p">(</span><span class="n">new_york_tz</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">paris</span> <span class="o">==</span> <span class="n">new_york</span><span class="p">,</span> <span class="n">paris</span><span class="o">.</span><span class="n">date</span><span class="p">()</span> <span class="o">==</span> <span class="n">new_york</span><span class="o">.</span><span class="n">date</span><span class="p">()</span>
<span class="go">(True, False)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">paris</span> <span class="o">-</span> <span class="n">new_york</span><span class="p">,</span> <span class="n">paris</span><span class="o">.</span><span class="n">date</span><span class="p">()</span> <span class="o">-</span> <span class="n">new_york</span><span class="o">.</span><span class="n">date</span><span class="p">()</span>
<span class="go">(datetime.timedelta(0), datetime.timedelta(1))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">paris</span>
<span class="go">datetime.datetime(2012, 3, 3, 1, 30, tzinfo=&lt;DstTzInfo &#39;Europe/Paris&#39; CET+1:00:00 STD&gt;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">new_york</span>
<span class="go">datetime.datetime(2012, 3, 2, 19, 30, tzinfo=&lt;DstTzInfo &#39;America/New_York&#39; EST-1 day, 19:00:00 STD&gt;)</span>
</pre></div>
</div>
<p>As this example shows, the same datetime has a different date, depending on
the time zone in which it is represented. But the real problem is more
fundamental.</p>
<p>A datetime represents a <strong>point in time</strong>. It's absolute: it doesn't depend
on anything. On the contrary, a date is a <strong>calendaring concept</strong>. It's a
period of time whose bounds depend on the time zone in which the date is
considered. As you can see, these two concepts are fundamentally different,
and converting a datetime to a date isn't a deterministic operation.</p>
<p>What does this mean in practice?</p>
<p>Generally, you should avoid converting a <a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.datetime" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> to
<a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.date" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a>. For instance, you can use the <a class="reference internal" href="../../ref/templates/builtins.html#std:templatefilter-date"><code class="xref std std-tfilter docutils literal notranslate"><span class="pre">date</span></code></a>
template filter to only show the date part of a datetime. This filter will
convert the datetime into the current time zone before formatting it,
ensuring the results appear correctly.</p>
<p>If you really need to do the conversion yourself, you must ensure the
datetime is converted to the appropriate time zone first. Usually, this
will be the current timezone:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.utils</span> <span class="kn">import</span> <span class="n">timezone</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">timezone</span><span class="o">.</span><span class="n">activate</span><span class="p">(</span><span class="n">pytz</span><span class="o">.</span><span class="n">timezone</span><span class="p">(</span><span class="s2">&quot;Asia/Singapore&quot;</span><span class="p">))</span>
<span class="go"># For this example, we set the time zone to Singapore, but here&#39;s how</span>
<span class="go"># you would obtain the current time zone in the general case.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">current_tz</span> <span class="o">=</span> <span class="n">timezone</span><span class="o">.</span><span class="n">get_current_timezone</span><span class="p">()</span>
<span class="go"># Again, this is the correct way to convert between time zones with pytz.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">local</span> <span class="o">=</span> <span class="n">current_tz</span><span class="o">.</span><span class="n">normalize</span><span class="p">(</span><span class="n">paris</span><span class="o">.</span><span class="n">astimezone</span><span class="p">(</span><span class="n">current_tz</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">local</span>
<span class="go">datetime.datetime(2012, 3, 3, 8, 30, tzinfo=&lt;DstTzInfo &#39;Asia/Singapore&#39; SGT+8:00:00 STD&gt;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">local</span><span class="o">.</span><span class="n">date</span><span class="p">()</span>
<span class="go">datetime.date(2012, 3, 3)</span>
</pre></div>
</div>
</li>
<li><p class="first"><strong>I get an error</strong> &quot;<code class="docutils literal notranslate"><span class="pre">Are</span> <span class="pre">time</span> <span class="pre">zone</span> <span class="pre">definitions</span> <span class="pre">for</span> <span class="pre">your</span> <span class="pre">database</span>
<span class="pre">installed?</span></code>&quot;</p>
<p>If you are using MySQL, see the <a class="reference internal" href="../../ref/databases.html#mysql-time-zone-definitions"><span class="std std-ref">时区定义</span></a> section
of the MySQL notes for instructions on loading time zone definitions.</p>
</li>
</ol>
</div>
<div class="section" id="s-usage">
<span id="usage"></span><h3>Usage<a class="headerlink" href="#usage" title="永久链接至标题">¶</a></h3>
<ol class="arabic">
<li><p class="first"><strong>I have a string</strong> <code class="docutils literal notranslate"><span class="pre">&quot;2012-02-21</span> <span class="pre">10:28:45&quot;</span></code> <strong>and I know it's in the</strong>
<code class="docutils literal notranslate"><span class="pre">&quot;Europe/Helsinki&quot;</span></code> <strong>time zone. How do I turn that into an aware
datetime?</strong></p>
<p>This is exactly what <a class="reference external" href="http://pytz.sourceforge.net/">pytz</a> is for.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.utils.dateparse</span> <span class="kn">import</span> <span class="n">parse_datetime</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">naive</span> <span class="o">=</span> <span class="n">parse_datetime</span><span class="p">(</span><span class="s2">&quot;2012-02-21 10:28:45&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">pytz</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pytz</span><span class="o">.</span><span class="n">timezone</span><span class="p">(</span><span class="s2">&quot;Europe/Helsinki&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">localize</span><span class="p">(</span><span class="n">naive</span><span class="p">,</span> <span class="n">is_dst</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span>
<span class="go">datetime.datetime(2012, 2, 21, 10, 28, 45, tzinfo=&lt;DstTzInfo &#39;Europe/Helsinki&#39; EET+2:00:00 STD&gt;)</span>
</pre></div>
</div>
<p>Note that <code class="docutils literal notranslate"><span class="pre">localize</span></code> is a pytz extension to the <a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.tzinfo" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a>
API. Also, you may want to catch <code class="docutils literal notranslate"><span class="pre">pytz.InvalidTimeError</span></code>. The
documentation of pytz contains <a class="reference external" href="http://pytz.sourceforge.net/#example-usage">more examples</a>. You should review it
before attempting to manipulate aware datetimes.</p>
</li>
<li><p class="first"><strong>How can I obtain the local time in the current time zone?</strong></p>
<p>Well, the first question is, do you really need to?</p>
<p>You should only use local time when you're interacting with humans, and the
template layer provides <a class="reference internal" href="#time-zones-in-templates"><span class="std std-ref">filters and tags</span></a>
to convert datetimes to the time zone of your choice.</p>
<p>Furthermore, Python knows how to compare aware datetimes, taking into
account UTC offsets when necessary. It's much easier (and possibly faster)
to write all your model and view code in UTC. So, in most circumstances,
the datetime in UTC returned by <a class="reference internal" href="../../ref/utils.html#django.utils.timezone.now" title="django.utils.timezone.now"><code class="xref py py-func docutils literal notranslate"><span class="pre">django.utils.timezone.now()</span></code></a> will be
sufficient.</p>
<p>For the sake of completeness, though, if you really want the local time
in the current time zone, here's how you can obtain it:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.utils</span> <span class="kn">import</span> <span class="n">timezone</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">timezone</span><span class="o">.</span><span class="n">localtime</span><span class="p">(</span><span class="n">timezone</span><span class="o">.</span><span class="n">now</span><span class="p">())</span>
<span class="go">datetime.datetime(2012, 3, 3, 20, 10, 53, 873365, tzinfo=&lt;DstTzInfo &#39;Europe/Paris&#39; CET+1:00:00 STD&gt;)</span>
</pre></div>
</div>
<p>In this example, the current time zone is <code class="docutils literal notranslate"><span class="pre">&quot;Europe/Paris&quot;</span></code>.</p>
</li>
<li><p class="first"><strong>How can I see all available time zones?</strong></p>
<p><a class="reference external" href="http://pytz.sourceforge.net/">pytz</a> provides <a class="reference external" href="http://pytz.sourceforge.net/#helpers">helpers</a>, including a list of current time zones and a list
of all available time zones -- some of which are only of historical
interest. <a class="reference external" href="https://docs.python.org/3/library/zoneinfo.html#module-zoneinfo" title="(在 Python v3.9)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">zoneinfo</span></code></a> also provides similar functionality via
<a class="reference external" href="https://docs.python.org/3/library/zoneinfo.html#zoneinfo.available_timezones" title="(在 Python v3.9)"><code class="xref py py-func docutils literal notranslate"><span class="pre">zoneinfo.available_timezones()</span></code></a>.</p>
</li>
</ol>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Time zones</a><ul>
<li><a class="reference internal" href="#overview">Overview</a></li>
<li><a class="reference internal" href="#concepts">Concepts</a><ul>
<li><a class="reference internal" href="#naive-and-aware-datetime-objects">Naive and aware datetime objects</a></li>
<li><a class="reference internal" href="#interpretation-of-naive-datetime-objects">Interpretation of naive datetime objects</a></li>
<li><a class="reference internal" href="#default-time-zone-and-current-time-zone">Default time zone and current time zone</a></li>
<li><a class="reference internal" href="#selecting-the-current-time-zone">Selecting the current time zone</a></li>
</ul>
</li>
<li><a class="reference internal" href="#time-zone-aware-input-in-forms">Time zone aware input in forms</a></li>
<li><a class="reference internal" href="#time-zone-aware-output-in-templates">Time zone aware output in templates</a><ul>
<li><a class="reference internal" href="#template-tags">Template tags</a><ul>
<li><a class="reference internal" href="#localtime"><code class="docutils literal notranslate"><span class="pre">localtime</span></code></a></li>
<li><a class="reference internal" href="#timezone"><code class="docutils literal notranslate"><span class="pre">timezone</span></code></a></li>
<li><a class="reference internal" href="#get-current-timezone"><code class="docutils literal notranslate"><span class="pre">get_current_timezone</span></code></a></li>
</ul>
</li>
<li><a class="reference internal" href="#template-filters">Template filters</a><ul>
<li><a class="reference internal" href="#std:templatefilter-localtime"><code class="docutils literal notranslate"><span class="pre">localtime</span></code></a></li>
<li><a class="reference internal" href="#utc"><code class="docutils literal notranslate"><span class="pre">utc</span></code></a></li>
<li><a class="reference internal" href="#std:templatefilter-timezone"><code class="docutils literal notranslate"><span class="pre">timezone</span></code></a></li>
</ul>
</li>
</ul>
</li>
<li><a class="reference internal" href="#migration-guide">Migration guide</a><ul>
<li><a class="reference internal" href="#database">Database</a><ul>
<li><a class="reference internal" href="#postgresql">PostgreSQL</a></li>
<li><a class="reference internal" href="#other-databases">Other databases</a></li>
</ul>
</li>
<li><a class="reference internal" href="#code">Code</a></li>
<li><a class="reference internal" href="#fixtures">Fixtures</a></li>
</ul>
</li>
<li><a class="reference internal" href="#faq">FAQ</a><ul>
<li><a class="reference internal" href="#setup">Setup</a></li>
<li><a class="reference internal" href="#troubleshooting">Troubleshooting</a></li>
<li><a class="reference internal" href="#usage">Usage</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="formatting.html"
                        title="上一章">Format localization</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="../logging.html"
                        title="下一章">Logging</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../../_sources/topics/i18n/timezones.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">7月 23, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="formatting.html" title="Format localization">previous</a>
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="../logging.html" title="Logging">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>